package com.my.test.thread.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 可以被2个线程同时获取，共享锁
 */
public class TwoLocks implements Lock {

    private final Sync sync = new Sync(2);

    private static final class Sync extends AbstractQueuedSynchronizer{

        /**
         * 构造方法 ，初始化状态
         * @param count
         */
        public Sync (int count){
            if (count < 0 ){
                throw new IllegalArgumentException("count must large than 0");
            }
            setState(count);
        }

        /**
         * 共享的方式获得锁
         * @param reduceCount
         * @return
         */
        public int tryAcquireShared(int reduceCount) {
            for (;;){
                int current = getState();
                int newCount = current - reduceCount;
                if (newCount < 0 || compareAndSetState(current,newCount)) {
                    return newCount;
                }
            }


        }

        /**
         * 共享的方式释放锁
         * @param returnCount
         * @return
         */
        protected boolean tryReleaseShared(int returnCount) {
            for (;;) {
                int current = getState();
                int newCount = current + returnCount;
                if (compareAndSetState(current,newCount)) {
                    return true;
                }
            }
        }

    }

    @Override
    public void lock() {
        sync.tryAcquireShared(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        sync.releaseShared(1);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
